package com.catsic.core.rmi;

import java.util.List;
import java.util.Properties;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.remoting.rmi.RmiServiceExporter;


/**
 * 发布所有服务
 * @author 马英杰
 *
 */
public class IssueServices {
	
	private ApplicationContext context;

	/**
	 * 根据配置文件发布所有对客户端的服务
	 * @param props server.properties配置文件
	 * @return
	 */
	public int IssueByConfige(ApplicationContext context , Properties props){
		
		//配置RMI服务
		if(props.getProperty("rmi.server").equals("true")){
			//接口文件所在包名
			String packages=props.getProperty("rmi.package");
			//rmi使用端口
			String port=props.getProperty("rmi.port");
			CatsRmiServer crs = new CatsRmiServer();
			//找到所有RMI接口
			List<String> classlist = crs.IssueServices(packages);
			for(int i = 0; i < classlist.size(); i++ )
				if( ( (String) classlist.get(i) ).indexOf("Service")<1 ){
					classlist.remove(i);
					i--;
				}
			if( classlist.size()<1)
				System.out.println("没有找到rmi服务");
			else
				//为Spring注册所有rmi发布bean
				StartRMIServices(context,classlist,(port.length()>0?Integer.parseInt(port):8888));
		}
		else{
			System.out.println("根据配置，不需要启动rmi服务");
		}
		
		return 0;
	}
	
	@SuppressWarnings("unused")
	private void StartRMIServices(ApplicationContext context,List<String> classlist,int port){
		//循环，将所有RMI接口注册为bean
		this.context = context;
		for(int i=0;i<classlist.size();i++){
			String classall = classlist.get(i);
			String beanname = altFirstChar(classall.substring(classall.lastIndexOf(".")+1));
			
			if (context.containsBean(beanname)) {  
				Class<?> serviceClass = getServiceClass("org.springframework.remoting.rmi.RmiServiceExporter");  
				BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(serviceClass);  
				beanDefinitionBuilder.addPropertyValue("service", context.getBean(beanname));
				beanDefinitionBuilder.addPropertyValue("serviceName", beanname);
				beanDefinitionBuilder.addPropertyValue("serviceInterface", classall);
				beanDefinitionBuilder.addPropertyValue("registryPort", port);
				
				//注册RMI bean
				registerBean(beanname+"RMI", beanDefinitionBuilder.getRawBeanDefinition());  
				
				//发布RMI bean
				RmiServiceExporter obj = (RmiServiceExporter)context.getBean(beanname+"RMI");
			}
			
			
		}
	}
	
	/**  
	 * @desc 向spring容器注册bean  
	 * @param beanName  
	 * @param beanDefinition  
	 */ 
	private void registerBean(String beanName, BeanDefinition beanDefinition) {  
		ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) context;  
		BeanDefinitionRegistry beanDefinitonRegistry = (BeanDefinitionRegistry) configurableApplicationContext.getBeanFactory();  
		beanDefinitonRegistry.registerBeanDefinition(beanName, beanDefinition);  
	}  

	/**
	 * 小些首字母
	 * @param s
	 * @return
	 */
	private String altFirstChar(String s){
		if(Character.isLowerCase(s.charAt(0)))
			return s;
		else
			return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString(); 
	}
	
    /**  
     * @desc 根据类名查找class  
     * @param className  
     * @return  
     * @throws BVSException  
     */ 
	private Class<?> getServiceClass(String className){  
		try {  
			return Thread.currentThread().getContextClassLoader().loadClass(className);  
		} catch (ClassNotFoundException e) {  
			//log.error("not found service class:" + className, e);  
			//throw new BVSException("not found service class:" + className, e);  
			return null;
		}  
	}  

}
